import { _decorator, Button, Node, Label } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { gm } from '../../../../scripts/managers/GameManager';
import { concat, forkJoin, Observable } from 'rxjs';
import { am } from '../../../../scripts/managers/AudioManager';
import { Timer } from '../../../../scripts/libs/rxjs/cc3/CreatorSchedule';
import { TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
import { UIOpacity } from 'cc';
import { thinking_sdk_m } from '../../../../scripts/managers/SDK/ThinkingCocosSDKManager';
import { udm } from '../../../../scripts/managers/UserDataManager';
import { adsm } from '../../../../scripts/managers/AdsManager';
import { StageInfo } from '../../game/basic';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { DevConfig } from '../../../../scripts/managers/DevConfig';
import { ChestOpenPanel } from '../ChestOpenPanel/ChestOpenPanel';
import { lm } from '../../LobbyManager';
import { timem } from '../../../../scripts/managers/TimeManager';
import { applovin_sdk_m } from '../../../../scripts/managers/SDK/AppLovinCocosSDKManager';
const { ccclass, property } = _decorator;

@ccclass('EditorGameWinPanel')
export class EditorGameWinPanel extends BasePanel {

    stageInfo = ReactiveProperty.Create<StageInfo>(null);

    @property(Node)
    bgNode: Node = null;

    @property(Node)
    mainNode: Node = null;

    @property(Button)
    retryButton: Button = null;

    @property(Button)
    exitButton: Button = null;

    @property(Button)
    adsButton: Button = null;

    @property(Button)
    nextButton: Button = null;

    @property(Button)
    editButton: Button = null;

    @property(Label)
    stageChestLabel: Label = null;

    willBind(): void {
        gm.currentAdsType.value = 'AdWinDouble';
        gm.currentAdsOpenUI.value = 'GameWinPanel';
        gm.currentInterstitialAdsType.value = 'AdWin';
        this.bgNode.getComponent(UIOpacity).opacity = 0;
        this.mainNode.getComponent(UIOpacity).opacity = 0;
    }

    useObserves() {
        return [
            gm.editEnabled.subscribe(_ => {
                this.exitButton.node.active = _;
                this.retryButton.node.active = _;
                this.editButton.node.active = _;
                this.adsButton.node.active = !_;
                this.nextButton.node.active = !_;
            }),
            BindButton(this.retryButton).subscribe(this.retryButtonClicked.bind(this)),
            BindButton(this.exitButton).subscribe(this.exitButtonClicked.bind(this)),
            BindButton(this.nextButton).subscribe(this.nextButtonClicked.bind(this)),
            BindButton(this.editButton).subscribe(this.editButtonClicked.bind(this)),
            BindButton(this.adsButton).subscribe(this.adsButtonClicked.bind(this)),
            this.stageInfo.subscribe(this.refresh.bind(this)),
        ];
    }

    openPanelAnim(): Observable<any> {
        this.ensureUIOpacity().opacity = 255;
        am.playSfx({ clipName: `ab_lobby/Audio/sfx/LevelCompleted` });
        return concat(
            Timer(1, this.node),
            forkJoin([
                TweenToStart(this.bgNode.getComponent(UIOpacity), 1, { opacity: 255 }, { easing: 'expoOut' }),
                TweenToStart(this.mainNode.getComponent(UIOpacity), 1, { opacity: 255 }, { easing: 'expoOut' })
            ])
        );
    }

    _already_track_ads_show = false;
    waitingChest = false;
    refresh() {
        if (this.stageInfo.value == null) return;
        let { chestCurValue, chestMaxValue, flag } = udm.checkStageChestProgress(this.stageInfo.value.stageId);
        this.stageChestLabel.string = `Stage Chest Progress: ${chestCurValue} / ${chestMaxValue}`;

        if (this.stageInfo.value.stageId >= DevConfig.REWARDEDAD_FROM_STAGE_NUM) {
            this.adsButton.node.active = true;
            if (!this._already_track_ads_show) {
                this._already_track_ads_show = true;
                thinking_sdk_m.requestTrack('Ads_Show', {
                    AdsType: gm.currentAdsType.value,
                    OpenUI: gm.currentAdsOpenUI.value,
                    IsNew: udm.isNew.value
                });
            }
        } else {
            this.adsButton.node.active = false;
        }

        if (udm.stageChest.value != null) {
            this.waitingChest = true;
            Timer(2, this.node).subscribe(_ => {
                ChestOpenPanel.StartProcess((panel: ChestOpenPanel) => {
                    panel.stageInfo.value = this.stageInfo.value;
                    panel.key.value = udm.stageChest.value;
                }).subscribe(_ => {
                    this.waitingChest = false;
                });
            }).addTo(this.node);
        }
    }

    retryButtonClicked() {
        udm.temp_coin_diff.value = null;
        gm.coinAnimatingFlags.delete('over_anim');
        EditorGameWinPanel.CloseProcess(null, 'retry');
    }

    exitButtonClicked() {
        udm.temp_coin_diff.value = null;
        gm.coinAnimatingFlags.delete('over_anim');
        EditorGameWinPanel.CloseProcess(null, 'exit');
    }

    nextButtonClicked() {
        if (this.waitingChest) {
            lm.frontTipShow('Waiting...');
            return;
        }
        udm.temp_coin_diff.value = null;
        gm.coinAnimatingFlags.delete('over_anim');

        if (udm.noAds.value == 0) { // 条件：没买去广告

            if (!udm.isNew.value) { // 条件：不是新用户

                if (this.stageInfo.value.stageId >= DevConfig.INTERSTITIALAD_FROM_STAGE_NUM) { // 条件：大于等于x关

                    // 需要隔天的条件已经去除
                    // let firstLoginDayAt = new Date(udm.firstLoginAt.value);
                    // firstLoginDayAt.setHours(0, 0, 0, 0);
                    // let nowDayAt = timem.getCurrentDate();
                    // nowDayAt.setHours(0, 0, 0, 0);
                    // this.log('nowDayAt/firstLoginDayAt', nowDayAt.valueOf(), firstLoginDayAt.valueOf());

                    // if (nowDayAt.valueOf() > firstLoginDayAt.valueOf()) { // 条件：需要隔天

                    let CD = undefined;
                    if (udm.interstitialAt.value != null) {
                        CD = (timem.now() - udm.interstitialAt.value) / 1000;
                    }
                    this.log('interstitialAd CD:', CD, 'need greator than:', DevConfig.INTERSTITIALAD_CD);

                    if (CD == null || CD >= DevConfig.INTERSTITIALAD_CD) { // 条件:需要CD
                        applovin_sdk_m.requestIsReadyInterstitialAd().subscribe(isReady => {
                            thinking_sdk_m.requestTrack('Ads_Interstitial_Stage', {
                                AdsType: gm.currentInterstitialAdsType.value,
                                Level_ID: this.stageInfo.value.stageId,
                                Times: udm.interstitialAdTimes.value,
                                CD,
                                CD_Status: "CD_Enough",
                                ad_progress: isReady ? 'Load' : 'LoadFail',
                                IsNew: udm.isNew.value
                            });
                            if (isReady) {
                                thinking_sdk_m.requestTrack('Ads_Interstitial_Show', {
                                    AdsType: gm.currentInterstitialAdsType.value,
                                    Level_ID: this.stageInfo.value.stageId,
                                    Times: udm.interstitialAdTimes.value,
                                    IsNew: udm.isNew.value
                                });
                                // udm.interstitialAt.value = timem.now();
                                // udm.save();
                                applovin_sdk_m.stageNum.value = this.stageInfo.value.stageId;
                                applovin_sdk_m.requestShowInterstitialAd();
                            }
                        });
                    } else {
                        applovin_sdk_m.requestIsReadyInterstitialAd().subscribe(isReady => {
                            thinking_sdk_m.requestTrack('Ads_Interstitial_Stage', {
                                AdsType: gm.currentInterstitialAdsType.value,
                                Level_ID: this.stageInfo.value.stageId,
                                Times: udm.interstitialAdTimes.value,
                                CD,
                                CD_Status: "CD_Low",
                                ad_progress: isReady ? 'Load' : 'LoadFail',
                                IsNew: udm.isNew.value
                            });
                        });
                    }
                    // }
                }
            }
        }


        EditorGameWinPanel.CloseProcess(null, 'next');
    }

    editButtonClicked() {
        udm.temp_coin_diff.value = null;
        gm.coinAnimatingFlags.delete('over_anim');
        EditorGameWinPanel.CloseProcess(null, 'edit');
    }

    adsButtonClicked() {
        if (this.waitingChest) {
            lm.frontTipShow('Waiting...');
            return;
        }
        thinking_sdk_m.requestTrack('Ads_Click', {
            AdsType: gm.currentAdsType.value,
            OpenUI: gm.currentAdsOpenUI.value,
            IsNew: udm.isNew.value
        });
        adsm.showRewardAds('stage_completed_double_reward').subscribe(_ => {
            if (_ == 'success') {
                thinking_sdk_m.requestTrack('Ads_Return', {
                    AdsType: gm.currentAdsType.value,
                    OpenUI: gm.currentAdsOpenUI.value,
                    IsNew: udm.isNew.value
                });

                // let hard = this.stageInfo.value.hard;
                thinking_sdk_m.requestTrack('Coins_Get', {
                    CoinNum: DevConfig.COIN_COMPLETED_EARN_ADS - DevConfig.COIN_COMPLETED_EARN,
                    Type: 'LevelWinDouble',
                    Gift_Detail: 'Other',
                    IsNew: udm.isNew.value,
                    Level_ID: this.stageInfo.value.stageId,
                });

                this.mainNode.active = false;

                // Timer(2, this.node).subscribe(_ => {
                udm.coin.value += DevConfig.COIN_COMPLETED_EARN_ADS - DevConfig.COIN_COMPLETED_EARN;
                udm.save();

                udm.temp_coin_diff.value = null;
                gm.coinAnimatingFlags.delete('over_anim');
                EditorGameWinPanel.CloseProcess(null, 'next');
                // });

            }
        });
    }
}


